package com.sikaryofficial.backend.manager;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sikaryofficial.backend.constant.FeedbackTypeEnum;
import com.sikaryofficial.backend.domain.dto.req.FeedbackReq;
import com.sikaryofficial.backend.domain.entity.UserFeedback;
import com.sikaryofficial.backend.service.IUserFeedbackService;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.RemoteUserService;
import com.sikaryofficial.system.api.model.SysMemberReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc : 用户反馈管理服务
 * @date : 2023/10/30 15:39
 */
@Service
@Slf4j
public class UserFeedbackManager {
    @Autowired
    private IUserFeedbackService feedbackService;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 保存反馈
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveFeedback(FeedbackReq req) {

        FeedbackTypeEnum feedbackTypeEnum = FeedbackTypeEnum.getNameByCode(req.getFeedbackType());
        if (Objects.isNull(feedbackTypeEnum)) {
            throw new IllegalArgumentException("Feedback type error.");
        }
        UserFeedback feedback = new UserFeedback();
        feedback.setCreatedBy(SecurityUtils.getUserId());
        feedback.setCreatedTime(new Date());
        feedback.setFeedbackId(IdWorker.getId());
        feedback.setFeedbackType(req.getFeedbackType());
        feedback.setReason(req.getReason());
        feedbackService.save(feedback);
        Long userId = SecurityUtils.getUserId();
        switch (feedbackTypeEnum) {
            case UNSUBSCRIBE:
                unsubscribeOmner(userId);
                break;
            case DELETE_PERSONAL_DATA:
                // 删除账号对应的用户数据
                feedbackService.deleteUserDataByUserId(SecurityUtils.getUserId());
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 注销自己的账号
     *
     * @param userId
     */
    private void unsubscribeOmner(Long userId) {
        try {
            // 删除账号
            remoteUserService.deleteUserByOwner(new Long[]{userId});
            // 删除账号对应的用户数据
            feedbackService.deleteUserDataByUserId(SecurityUtils.getUserId());
        } catch (Exception e) {
            log.error("删除账号失败", e);
            throw new ServiceException("Account deletion failed");
        }
    }

    /**
     * 注销会员
     *
     * @param userId
     */
    private void unsubscribeMember(Long userId) {
        try {
            // 删除账号
            remoteUserService.deleteMemberUsers(new Long[]{userId});
            // 删除账号对应的用户数据
            feedbackService.deleteUserDataByUserId(SecurityUtils.getUserId());
        } catch (Exception e) {
            log.error("删除账号失败", e);
            throw new ServiceException("Account deletion failed");
        }
    }

    public boolean unsubscribe(SysMemberReq req) {
        // 逗号分隔未数组，并遍历 req.getUserIds()
        if (req.getUserIds() != null && !req.getUserIds().isEmpty()) {
            String[] userIds = req.getUserIds().split(",");
            Arrays.stream(userIds).forEach(userId -> unsubscribeMember(Long.valueOf(userId)));
            return true;
        }
        return false;
    }
}
